import { preferences } from '@kit.ArkData';

const TAG = 'myPerferences';

class PreferencesUtil{
  //实例
  myPreferences: preferences.Preferences | null = null;

  //创建实例
  createPreferences(content){
    try {
      this.myPreferences = preferences.getPreferencesSync(content, {
        name: 'myPerferences'
      });
      console.log(TAG, '实例创建成功');
    }catch (err){
      console.log(TAG, '实例创建失败' + JSON.stringify(err));
    };
  };

  //设置
  async put(key: string, val: preferences.ValueType){
    if(!this.myPreferences){
      console.log(TAG, '实例未创建');
      return;
    }
    try{
      this.myPreferences.putSync(key, val);
      await this.myPreferences.flush();
      console.log(TAG, `设置${key}成功`);
    }catch (err){
      console.log(TAG, `设置${key}失败` + JSON.stringify(err));
    }
  };

  //获取
  get(key: string, defaults:preferences.ValueType = '默认值'){
    if(!this.myPreferences){
      console.log(TAG, '实例未创建');
      return;
    }
    try{
      let res = this.myPreferences.getSync(key, defaults);
      console.log(TAG, `获取${key}成功`);
      return res;
    }catch (err){
      console.log(TAG, `获取${key}失败` + JSON.stringify(err));
    }
  };

  //获取
  getAll(){
    if(!this.myPreferences){
      console.log(TAG, '实例未创建');
      return;
    }
    try{
      let res = this.myPreferences.getAllSync();
      console.log(TAG, `获取所有成功`);
      return res;
    }catch (err){
      console.log(TAG, `获取所有失败` + JSON.stringify(err));
    }
  };

  //获取
  del(key: string){
    if(!this.myPreferences){
      console.log(TAG, '实例未创建');
      return;
    }
    try{
      let res = this.myPreferences.deleteSync(key);
      console.log(TAG, `删除${key}成功`);
      return res;
    }catch (err){
      console.log(TAG, `删除${key}失败` + JSON.stringify(err));
    }
  }
}
export default new PreferencesUtil();